<?php
namespace app\frontend\forms;

use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Password;

use Phalcon\Validation\Validator\Callback;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Confirmation;
use app\models\User;

class LoginForm extends FormBase
{
    public $username;

    public $password;

    public $verifyCode;

    public $confirmVerifyCode;
    /** @var  User */
    private $_user;

    public function getUser()
    {
        return $this->_user;
    }

    public function initialize()
    {
        $this->setEntity($this);
        $verifyCode = new Text("verifyCode");
        $verifyCode->addValidators([
            new PresenceOf(['message'=>'验证码不能为空','cancelOnFail'=>true]),
            new Confirmation([
                'with'=>[
                    'verifyCode'=>'confirmVerifyCode',
                ],
                'message'=>'验证码不正确',
            ])
        ]);
        $this->add($verifyCode);

        $username = new Text("username");
        $username->addValidators([
            new PresenceOf(['message'=>'用户名不能为空']),
        ]);
        $this->add($username);

        $password = new Password("password");
        $password->addValidators([
            new PresenceOf(['message'=>'密码不能为空','cancelOnFail'=>true]),
            new Callback([
                'callback'=>function($data){
                    $currentModel = User::findFirst([
                        'username = :username: and password = :password:',
                        'bind'=>[
                            'username'=>$data['username'],
                            'password'=>$data['password'],
                        ]
                    ]);
                    $this->_user = $currentModel;
                    return $currentModel?true:false;
                },
                'message'=>'用户名或密码错误',
            ])
        ]);
        $this->add($password);
    }
}
